package com.cloudbroker.bcs.platform.ltb.middle.service.impl;

import com.alibaba.fastjson.JSON;
import com.cloudbroker.bcs.common.context.RuntimeContext;
import com.cloudbroker.bcs.common.zookeeper.NodeDataCacheListener;
import com.cloudbroker.bcs.common.zookeeper.ZooKeeperClient;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.vo.BlackKeyWordForm;
import com.cloudbroker.bcs.platform.ltb.middle.entity.BlackWord;
import com.cloudbroker.bcs.platform.ltb.middle.service.BlackWordService;
import com.cloudbroker.bcs.platform.ltb.middle.util.StringReplacer;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.List;

/**
 * Created by lili19289 on 2016/8/15.
 */
public class ZookeeperSubscriberListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZookeeperSubscriberListener.class);

    @Resource
    private BlackWordService blackWordService;

    private ZooKeeperClient client;

    public void init()throws Exception{
        client = RuntimeContext.getBean(ZooKeeperClient.class);
        client.start();
        if(!client.exists("/admin/blackword")){
            client.mkdirs("/admin/blackword");
        }
        client.watchData("/admin/blackword", new NodeDataCacheListener() {
            @Override
            public void nodeChanged(String path, byte[] data) {
                List<BlackWord> words = blackWordService.fetchAllBlackWords(new BlackKeyWordForm());
                StringReplacer.init(words);
            }
        });
        //设置节点的cache
//        final NodeCache nodeCache = new NodeCache(client.getCuratorFramework(), "/admin/blackword", false);
//        nodeCache.getListenable().addListener(new NodeCacheListener() {
//            @Override
//            public void nodeChanged() throws Exception {
//                System.er List<BlackWord> words = blackWordService.queryBlackWords(new BlackKeyWordForm());
//                LOGGER.info("敏感词更改————————————————————————————"+JSON.toJSONString(words));
//                StringReplacer.init(words);r.print("the blackword listnener ,the test node is change and result is :");
//                System.err.print("  path : "+nodeCache.getCurrentData().getPath());
//                System.err.print("  data : "+new String(nodeCache.getCurrentData().getData()));
//                System.err.print("  stat : "+nodeCache.getCurrentData().getStat());
//
//            }
//        });
//        nodeCache.start();
    }



}
